package com.budwk.app.sqfwDoc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfwDoc.dto.SqfwTemplateHistoryQueryDTO;
import com.budwk.app.sqfwDoc.models.SqfwTemplateHistory;
import com.budwk.app.sqfwDoc.service.SqfwTemplateHistoryService;
import com.budwk.app.sqfwDoc.vo.SqfwTemplateHistoryVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ZY.Wang
 * @since 2023/12/13
 */
@IocBean(args = {"refer:dao"})
public class SqfwTemplateHistoryServiceImpl extends BaseServiceImpl<SqfwTemplateHistory> implements SqfwTemplateHistoryService {
    public SqfwTemplateHistoryServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SysUserService sysUserService;

    @Override
    public List<SqfwTemplateHistoryVO> listTemplateHistory(SqfwTemplateHistoryQueryDTO queryDTO) {
        if (StringUtils.isBlank(queryDTO.getRelatedId())) {
            throw new ServiceException("业务id不能为空");
        }

        Cnd cnd = Cnd.NEW();
        cnd.and(SqfwTemplateHistory::getRelatedId, "=", queryDTO.getRelatedId());
        if (StringUtils.isNotBlank(queryDTO.getHistoryType())) {
            cnd.and(SqfwTemplateHistory::getHistoryType, "=", queryDTO.getHistoryType());
        }
        cnd.desc(SqfwTemplateHistory::getCreateTime);


        List<SqfwTemplateHistory> list = query(cnd);
        Set<String> userIdSet = Sets.newHashSet();
        for (SqfwTemplateHistory templateHistory : list) {
            userIdSet.add(templateHistory.getCreateBy());
            userIdSet.add(templateHistory.getUpdateBy());
        }
        List<Sys_user> sysUserList = sysUserService.query(Cnd.NEW().and(Sys_user::getId, "in", userIdSet));
        Map<String, Sys_user> userMap = sysUserList.stream().collect(Collectors.toMap(Sys_user::getId, item -> item));

        List<SqfwTemplateHistoryVO> resultList = Lists.newArrayList();
        for (SqfwTemplateHistory templateHistory : list) {
            SqfwTemplateHistoryVO vo = new SqfwTemplateHistoryVO();
            BeanUtil.copyProperties(templateHistory, vo);

            Sys_user createUser = userMap.get(vo.getCreateBy());
            Sys_user updateUser = userMap.get(vo.getUpdateBy());
            vo.setCreateUserName(createUser.getUsername());
            vo.setUpdateUserName(updateUser.getUsername());
            resultList.add(vo);
        }
        return resultList;
    }
}
